<?php

namespace App\Admin\Controllers;

use App\Exports\RuleExport;
use App\Model\Rule;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class RuleController extends AdminController
{
    /*
     * 展示优惠规则页面
     */
    public  function ruleShow(Request $request)
    {
        $where = function ($query) use ($request) {
            if ($request->has('rule_name') and $request->rule_name != '') {
                $search = "%" . $request->rule_name . "%";
                $query->where('rule_name', 'like', $search);
            }
            if ($request->has('rule_state') and $request->rule_state != '') {
                $search = "%" . $request->rule_state . "%";
                $query->where('rule_state', 'like', $search);
            }
        };

        //查询有信息
        $allData = Rule::where($where)->paginate(5);
        //渲染视图
        return view('rule.rule-show',compact('allData'));
    }
    /*
     * 展示添加页面
     */
   public  function  ruleAdd()
   {
       return view('rule.rule-add');
   }
   /*
    * 添加入库
    */
   public  function  ruleAddDo(Request $request)
   {
        //表单验证
       $request->validate([
           'rule_name' => 'required',
           'strat_time' => 'required',
           'end_time'  => 'required',
           'payFull'   => 'required',
           'payJian'   => 'required',
           'rule_active' => 'required'
       ],[
           'rule_name.required' =>'活动名称不能为空',
           'strat_time.required' =>'开始时间不能为空',
           'end_time.required' =>'结束时间不能为空',
           'payFull.required' =>'金额不能为空',
           'payJian.required' =>'金额不能为空',
           'rule_active.required' =>'活动规则不能为空',

       ]);
       //接收前台传来的数据
       $postData = $request->except(['_token']);

       //添加到数据库
       $res = Rule::create($postData);

       if($res){
           return redirect(route('admin.ruleShow'));
       }else{
           return false;
       }
   }

    /**
     * @param Request $request
     * @return array
     * 批量删除
     */
   public  function  deleteAll(Request $request)
   {
       //接收id
       $ids =  $request->get('id');
       //进行删除
       $res = Rule::destroy($ids);

       if ($res){
           return ['code'=>200,'msg'=>"删除成功",'data'=>[]];
       }else{
           return ['code'=>500,'msg'=>"删除失败",'data'=>[]];

       }
   }
   public  function  excel()
   {
       return Excel::download(new RuleExport, 'Rule.xlsx');
   }
}
